﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XCommunity.Caching;

namespace XCommunity.Documents
{

  /// <summary>
  /// 文档缓存容器，负责缓存文档
  /// </summary>
  public class DocumentCache : CacheContainer
  {

    /// <summary>
    /// 向缓存中添加一个文档
    /// </summary>
    /// <param name="document"></param>
    public void AddDocument( Document document )
    {
      AddItem( document.Meta.DocumentId, document );
    }


    /// <summary>
    /// 从缓存中获取文档
    /// </summary>
    /// <param name="documentId"></param>
    /// <returns></returns>
    public Document GetDocument( int documentId )
    {
      CacheItem item = TryGetAvailableItem( documentId );
      if ( item == null )
        return null;

      lock ( item )
      {
        item.ValueRefreshed();
        return (Document) item.TryGetValue();
      }
    }


    private long spanTicks = new TimeSpan( 0, 15, 0 ).Ticks;


    public override bool CheckAvailable( CacheItem cacheItem )
    {
      return Service.GetTicks() <= cacheItem.RefreshTime.Ticks + spanTicks;
    }
  }
}
